package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/authorInfo")
public class AuthorInfo extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    // 约定 get /authorInfo
    // 格式 application/json

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 拿到 blogId
        String blogId = req.getParameter("blogId");
        System.out.println("blogId=" + blogId);
        if(blogId == null){
            resp.setContentType("text.html; charset=utf8");
            resp.getWriter().write("请求中没有 blogId");
            return;
        }
        // 2. 根据 blogId 找到 userId
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.getBlogByBlogId(Integer.parseInt(blogId));
        if(blog == null){
            resp.setContentType("text.html; charset=utf8");
            resp.getWriter().write("没有找到 blogId");
            return;
        }
        int userId = blog.getUserId();
        System.out.println("userId=" + userId);
        // 3. 根据 userId 查询 user 信息
        UserDao userDao = new UserDao();
        User user = userDao.getUserByUserId(userId);
        if(user == null){
            resp.setContentType("text.html; charset=utf8");
            resp.getWriter().write("没有找到 userId");
            return;
        }
        // 4. 构建 json 字符串
        user.setPassword("");
        String respJson = objectMapper.writeValueAsString(user);
        // 5. 返回响应
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(respJson);
    }
}
